package org.demo.szml.perssionservice.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.demo.szml.perssionservice.repository.IPermissionRepository;
import org.demo.szml.perssionservice.repository.mapper.RolesMapper;
import org.demo.szml.perssionservice.repository.mapper.UserRolesMapper;
import org.demo.szml.perssionservice.repository.po.RolesPO;
import org.demo.szml.perssionservice.repository.po.UserRolesPO;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 权限仓储实现类
 * @date: 2025/6/16 13:55
 * @version: 1.0
 */
@Component
public class PermissionRepositoryImpl implements IPermissionRepository {

    private final UserRolesMapper userRolesMapper;

    private final RolesMapper rolesMapper;

    public PermissionRepositoryImpl(UserRolesMapper userRolesMapper,
                                 RolesMapper rolesMapper){
        this.userRolesMapper = userRolesMapper;
        this.rolesMapper = rolesMapper;
    }

    @Override
    public int bindDefaultRole(UserRolesPO userRolesPO) {
        return this.userRolesMapper.insert(userRolesPO);
    }

    @Override
    public Page<Long> getAttributeUsers(Long operatorId, Integer page, Integer size) {
        //查询操作者角色信息
        Page<UserRolesPO> userPage = new Page<>(page, size);
        UserRolesPO userRolesPO = userRolesMapper.selectOne(new LambdaQueryWrapper<UserRolesPO>()
                .select(UserRolesPO::getRoleId).eq(UserRolesPO::getUserId, operatorId));
        if(Objects.isNull(userRolesPO)){
            return null;
        }
        Integer roleId = userRolesPO.getRoleId();
        //查询操作者可查看的角色等级
        RolesPO rolesPO = rolesMapper.selectOne(new LambdaQueryWrapper<RolesPO>()
                .select(RolesPO::getRoleCode).eq(RolesPO::getRoleId, roleId));
        List<RolesPO> rolesPOS = rolesMapper.selectList(new LambdaQueryWrapper<RolesPO>()
                .select(RolesPO::getRoleId)
                .lt(RolesPO::getRoleCode, rolesPO.getRoleCode()));
        if(ObjectUtils.isEmpty(rolesPOS)){
            //如果角色信息为空 则无需进一步查找 直接返回本人信息
            Page<Long> result = new Page<>();
            result.setRecords(Collections.singletonList(operatorId));
            result.setTotal(1L);
            return result;
        }
        //查询符合权限要求的角色对应的用户Id信息
        Page<UserRolesPO> searchPage = userRolesMapper.selectPage(userPage,new LambdaQueryWrapper<UserRolesPO>()
                .select(UserRolesPO::getUserId));
        Page<Long> resultPage = new Page<>();
        resultPage.setRecords(searchPage.getRecords().stream().map(UserRolesPO::getUserId).collect(Collectors.toList()));
        resultPage.setTotal(searchPage.getTotal());
        return resultPage;
    }

    @Override
    public String getAttributeRelation(Long operatorId, Long userId) {
        //查询用户和操作者角色信息
        UserRolesPO userRole = userRolesMapper.selectOne(new LambdaQueryWrapper<UserRolesPO>()
                        .select(UserRolesPO::getRoleId)
                .eq(UserRolesPO::getUserId, userId));
        UserRolesPO operatorRole = userRolesMapper.selectOne(new LambdaQueryWrapper<UserRolesPO>()
                        .select(UserRolesPO::getRoleId)
                .eq(UserRolesPO::getUserId, operatorId));
        if(Objects.isNull(userRole) && Objects.isNull(operatorRole)){
            return "请求获取的用户信息不存在";
        }
        if(operatorRole.getRoleId().equals(userRole.getRoleId())){
            return "无权查看";
        }
        //查询角色对应的权限信息
        RolesPO userRolePO = rolesMapper.selectOne(new LambdaQueryWrapper<RolesPO>()
                .select(RolesPO::getRoleCode)
                .eq(RolesPO::getRoleId, userRole.getRoleId()));
        RolesPO operatorRolePO = rolesMapper.selectOne(new LambdaQueryWrapper<RolesPO>()
                .select(RolesPO::getRoleCode)
                .eq(RolesPO::getRoleId, operatorRole.getRoleId()));
        //返回对比的权限结果
        return operatorRolePO.getRoleCode().compareTo(userRolePO.getRoleCode())>0?null:"无权查看";
    }

    @Override
    public int rebindRole(Long operatorId,Long userId, Integer roleId) {
        //查找操作者和用户角色信息
        UserRolesPO operatorRoleId = userRolesMapper.selectOne(new LambdaQueryWrapper<UserRolesPO>()
                .select(UserRolesPO::getRoleId).eq(UserRolesPO::getUserId, operatorId));
        List<RolesPO> rolesPOS = rolesMapper.selectList(new LambdaQueryWrapper<RolesPO>()
                .select(RolesPO::getRoleId, RolesPO::getRoleCode).in(RolesPO::getRoleId, Arrays.asList(roleId, operatorRoleId.getRoleId())));
        if(ObjectUtils.isEmpty(rolesPOS)){
            return 0;
        }
        Map<Integer, String> roleMap = rolesPOS.stream().collect(Collectors.toMap(RolesPO::getRoleId, RolesPO::getRoleCode));
        //权限必须都存在
        if(!(roleMap.containsKey(roleId) && roleMap.containsKey(operatorRoleId.getRoleId()))){
            return 0;
        }
        if(roleMap.get(roleId).compareTo(roleMap.get(operatorRoleId.getRoleId()))>=0){
            //权限符合时才可以修改 不能越界 比如管理员无法提供超管的权限
            return 0;
        }
        UserRolesPO userRolesPO = new UserRolesPO();
        userRolesPO.setRoleId(roleId);
        userRolesPO.setUserId(userId);
        return userRolesMapper.update(userRolesPO, new LambdaUpdateWrapper<UserRolesPO>()
                .eq(UserRolesPO::getUserId, userId).set(UserRolesPO::getRoleId, roleId));
    }
}
